<template>
  <div>
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 成功读出excel文件的内容
    async handleSuccess({ results, header }) {
      try {
        this.tableData = results
        this.tableHeader = header
        // 1. 按接口文档要求，对读入的excel数据做格式转换
        const newData = this.transExcel(results, header)
        console.log('转换之后的数据', newData)
        // 2. 调用接口发请求
        await importEmployee(newData)
        this.$message.success('导入成功')
        this.$router.push('/employees')
      } catch (err) {
        console.log(err)
        this.$message.error(err)
      }
    },
    // 按接口文档要求，对读入的excel数据做格式转换
    // results excel表格的内容
    //    [
    //       {'姓名'：'小张'， '手机号': '13712345678'}
    //     , {.....}
    //    ]

    //  目标
    //  [
    //     {'username'：'小张'，'mobile': '13712345678'}
    //     , {.....}
    //  ]

    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })

        return enObj
      })
    }
  }
}
</script>
